// API - 动态路由

import { ElMessageBox } from "element-plus";
import router from "@/router";
import { http } from "@/utils/http";
import $config from "@/config";
import { arrayToTree } from "@/utils/truncate";
import { useUserStoreHook } from "@/store/modules/user";

/**
 * 获取当前用户路由
 *
 * @returns
 */
export const getAsyncMenusRoutes = () => {
  if ($config.router.localOnly) {
    return Promise.resolve<HttpResponse>({ data: [], message: "" });
  }
  const permissions = useUserStoreHook().permissions;
  return new Promise<HttpResponse>((resolve, reject) => {
    http
      .request<HttpResponse>("get", "/access/routes")
      .then(res => {
        resolve({
          ...res,
          data: arrayToTree(res.data, {
            transform: row => {
              if (
                row.type === "button" ||
                !permissions.includes(row.routeName)
              ) {
                return false;
              }
              const parent = res.data.find(
                (item: any) => item.id === row.parentId
              );
              const auths = res.data
                .filter(
                  (item: any) =>
                    item.parentId === row.id &&
                    item.type === "button" &&
                    permissions.includes(item.routeName)
                )
                .map((item: any) => item.routeName);
              return {
                path: row.path,
                name: row.routeName,
                component: row.component || undefined,
                redirect: row.redirect || undefined,
                meta: {
                  title: row.menuName,
                  icon: row.icon || undefined,
                  auths: auths,
                  //roles,
                  showLink: row.showLink,
                  showParent: row.showParent,
                  keepAlive: row.keepAlive,
                  frameSrc: row.frameSrc || undefined,
                  hiddenTag: row.hiddenTag,
                  fixedTag: row.fixedTag,
                  activePath: row.showLink ? undefined : parent?.path
                  //rank: row.sort
                }
              } as any;
            }
          })
        });
      })
      .catch(error => {
        ElMessageBox.alert(error.message, "系统消息", {
          customStyle: {
            verticalAlign: "top",
            top: "12vh"
          },
          confirmButtonText: "返回登录",
          closeOnClickModal: false,
          closeOnPressEscape: false,
          showClose: false,
          callback: () => {
            useUserStoreHook().logOut();
            if (router.currentRoute.value.name === "Login") {
              location.reload();
            }
          }
        });
        reject(error);
      });
  });
};
